package org.rabbitmq.consumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author: zhs
 * @Date: 2021/6/5 16:49
 * @Description:
 *
 * Publish / Subscribe 发布订阅模型
 *
 */
public class PublishSubscribeConsumer2 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2.设置参数
        factory.setHost("192.168.0.199"); //主机
        factory.setPort(5672); //端口
        factory.setVirtualHost("test"); //虚拟机
        factory.setUsername("root"); //用户名
        factory.setPassword("root"); //密码
        factory.setConnectionTimeout(5000);
        //3.获取链接 Connection
        Connection connection = factory.newConnection();
        //4.创建channel
        Channel channel = connection.createChannel();
        //5.
        String queueName = "fanout_queue_1";
        String queueName2 = "fanout_queue_2";
        Consumer consumer = new DefaultConsumer(channel){
            /**
             * 回调方法：收到消息后会自动执行该方法
             * @param consumerTag 消息标识
             * @param envelope 获取一些信息，交换机，路由key
             * @param properties 配置信息
             * @param body 真实数据
             * @throws IOException
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.err.println(new String(body));
                System.err.println("打印出来...");
            }
        };
        /**
         * String basicConsume(String queue, boolean autoAck, Consumer callback)
         * 参数：
         *  1.queue： 队列名称
         *  2.autoAck： 自动确认
         *  3.cancelCallback：
         */
        channel.basicConsume(queueName2,true,consumer);
    }
}
